package com.dongdong.mq;

import com.alibaba.dubbo.config.annotation.Reference;
import com.dongdong.pojo.TbOrder;
import com.dongdong.pojo.TbUser;
import com.dongdong.service.OrderService;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

@RocketMQTransactionListener(txProducerGroup = "dondong_score_group")
public class MQConsumerTransactionListener implements RocketMQLocalTransactionListener {

    @Reference
    private OrderService orderService;
    @Autowired
    private RedisTemplate redisTemplate;
   //消息的回调方法
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //消息的头信息
        MessageHeaders headers = message.getHeaders();
         //消息的具体内容,主要是给消费者用的
        String str = new String((byte[]) message.getPayload());
        //Object o提供者要用的数据
        try{
            //根据Object o 改订单状态
           TbOrder order = (TbOrder)o;
           String outTradeNo = order.getOutTradeNo().toString();
           String tradeNo = order.getTradeNo();
           orderService.updateByOutTrdateNo(outTradeNo,tradeNo);
        }catch (Exception e){
            e.printStackTrace();
            //进行事务的回滚
            redisTemplate.opsForValue().set(message.getHeaders().get("message"), "2");//回滚
           return RocketMQLocalTransactionState.ROLLBACK;
        }
        redisTemplate.opsForValue().set(message.getHeaders().get("message"), "1");//成功
        return RocketMQLocalTransactionState.COMMIT;
    }
    //消息的回查方法
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {

        //通过事务id获取 redis中 对应的本地事务执行状态
        String status = (String) redisTemplate.opsForValue().
                get(message.getHeaders().get("message").toString());
        if ("1".equals(status)) {
            return RocketMQLocalTransactionState.COMMIT;
        } else if ("2".equals(status)) {
            //继续处理，或者直接回滚
            return RocketMQLocalTransactionState.ROLLBACK;
        } else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }

}
